<!--
  @Descripttion：带弹窗选择的输入框组件
  @Author：zqy
  @Date：2020-10-17 14:27:39
  @Last Modified by：zqy
  @Last Modified time：2020-10-17 14:27:39
-->
<template>
  <div>
    <div class="select-with-search">
      <el-select
        ref="refSelect"
        v-model="selValue"
        filterable
        remote
        reserve-keyword
        clearable
        collapse-tags 
        :multiple="!!multiple"
        :placeholder="placeholder"
        no-match-text="无匹配结果"
        no-data-text="无匹配结果"
        :remote-method="remoteSelections"
        :loading="remoteLoading"
        @focus="getSelections"
        @change="handleSelectChange"
      >
        <el-option
          v-for="(item,index) in optionsData"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <i class="qup-select-input-search el-input__icon el-icon-search" @click.self="dialogShow=true" />
    </div>
    <el-dialog
      ref="refDlg"
      :title="config.title"
      :visible.sync="dialogShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="600px"
      append-to-body
      custom-class="qup-search-dlg"
      :show-close="false"
      @close="closeDialog"
    >
      <div slot="title" class="search-dlg-head">
        <div class="title">{{config.title}}</div>
        <div class="search-form-bar" @keydown.enter="handleSearch">
          <el-input size="mini" placeholder="请输入关键字" v-model="queryKeyWord" class="input-with-search">
            <el-button slot="append" size="mini" type="primary" @click="handleSearch">搜索</el-button>
          </el-input>
        </div>
      </div>
      <div class="qup-search-dlg">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="全部" name="all">
            <div class="table-list-box">
              <el-table
                ref="refTable"
                style="width: 100%"
                :data="tableData"
                :height="300"
                :row-key="primaryKey"
                :row-class-name="tableRowClassName"
                header-row-class-name="table-list-header"
                highlight-current-row
                border
                @selection-change="handleSelectionChange"
                @row-click="tableRowHandle"
              >
                <el-table-column v-if="multiple" type="selection" reserve-selection  width="50" fixed="left" align="center"/>
                <el-table-column 
                  v-for="(item,index) in cloumnData" 
                  :key="index" 
                  :prop="item.prop" 
                  :label="item.title" 
                  :min-width="item.width || 150" 
                />
              </el-table>
            </div>
            <el-button v-if="loadMore && tableData.length" class="btn-load-more" type="text" size="mini" @click="handlerLoadMore">
              加载更多数据 <i class="el-icon-arrow-down" />
            </el-button>
            <div v-if="!loadMore && tableData.length" class="no-more">没有更多数据了</div>
          </el-tab-pane>
          <el-tab-pane v-if="multiple" :label="`已选择(${tableSelectedData.length})`" name="selected">
            <div class="table-list-box">
              <el-table
                ref="refSelTable"
                style="width: 100%"
                :data="tableSelectedData"
                :height="340"
                header-row-class-name="table-list-header"
                highlight-current-row
                border
              >
                <el-table-column width="50" fixed="left" align="center">
                  <template slot="header" slot-scope="scope">
                      <span class="btn-clear" @click="handleClearAll">清空</span>
                  </template>
                  <template v-slot="{row}">
                    <i class="el-icon-error btn-remove" @click="handleRemoveSelecte(row)"></i>
                  </template>
                </el-table-column>
                <el-table-column 
                  v-for="(item,index) in cloumnData" 
                  :key="index" 
                  :prop="item.prop" 
                  :label="item.title" 
                  :min-width="item.width || 150" 
                />
              </el-table>
            </div>
            <!-- <div class="no-more"></div> -->
          </el-tab-pane>
        </el-tabs>
      </div>
      <div slot="footer">
        <el-button size="mini" @click="closeDialog">取消</el-button>
        <el-button size="mini" type="primary" class="btn-submit" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getRemoteData,getTableData} from "./apis";
export default {
  name: 'selectWithDialog',
  components: {},
  /* model: {
    prop: 'value',
    event: 'input'
  }, */
  props: {
    value:{
      default:''
    },
    remoteUrl:{
      type:String,
      default:''
    }, // apiUrl地址
    props:{
      type:Object,
      default:()=>{
        return {label: 'label', value: 'value'}
      }
    }, // 下拉选项的配置选项
    requestMethod:{
      type:String,
      default:'get'
    },
    paramField:{
      type:String,
      default:'keyWord'
    }, // 查询时关键字查询时的入参字段名称
    placeholder:{
      type:String,
      default:'请输入搜索'
    },
    multiple:{
      type:Boolean,
      default:false
    },//是否多选
    focusQuery:{
      type:Boolean,
      default:true
    },// 是否聚焦发起请求
    defualtOption:{
      type:Array,
      default:()=>[]
    },// 默认下拉框数据集合
    config:{
      type:Object,
      default:()=>{
        return {
          title:'',//弹窗标题
          interfacePath:'',//数据查询接口地址
          order:'',// 排序方式（desc/asc，降序/升序）
          sort:'',//排序字段名称
          setting:[
            {prop:'name',title:'名称',width:'150'},
            {prop:'code',title:'编码',width:'150'},
          ]
        }
      }
    }
  },
  data() {
    return {
      remoteLoading: false, // 远程搜索加载
      optionsData:[], //下拉框数据集合
      selectedData:[], // 当前所选中的数据对象，对应props中{label,value}
      selValue:'',//当前所选中的值，对应props的value
      dialogShow:false,
      activeTab:'all',
      tableData:[],//表格全部数据
      selectedRows:[],//表格已选择数据行
      singleRows:[],//单选数据行
      tableSelectedData:[],//已选表格数据
      loadMore:false,//是否加载更多
      queryKeyWord:'',//查询关键字
      page:1, 
      pageSize:15
    }
  },

  computed: {
    // 表格主键
    primaryKey(){
      return this.props.value || 'id'
    },
    // 表格列
    cloumnData(){
      return this.config.setting || []
    }
  },
  watch:{
    dialogShow:{
      handler(val,oldVal){
        if(val && this.tableData.length===0){
          this.queryTableData()
        }
      },
      immediate:true
    },
    defualtOption:{
      handler(val,oldVal){
        this.optionsData= val || []
      },
      immediate:true,
      deep:true
    },
    value:{
      handler(val,oldVal){
        this.selValue=Array.isArray(val)?val:`${val}`
      },
      immediate:true
    },
    selValue(val,oldVal){
      this.$emit('input', val)
    }
  },
  methods: {
    // 关闭弹窗
    closeDialog(){
      this.dialogShow=false
    },
    // 确定
    handleSubmit(){
      const selValue = []
      const rows = this.multiple ? this.tableSelectedData : this.singleRows

      this.optionsData = rows.map(v=>{
        selValue.push(v[this.props.value])
        return {
          label:v[this.props.label],
          value:v[this.props.value]
        }
      })
      if(this.multiple){
        this.selectedData=this.optionsData
        this.selValue = selValue
      }else{
        this.selectedData=this.optionsData.length?this.optionsData[0]:[]
        this.selValue = this.optionsData.length?selValue[0]:''
      }
      this.closeDialog()
    },
    // 文本框值改变
    handleSelectChange() {
      this.$forceUpdate()
      // this.$emit("change", this.selValue)
    },
    // 获取下拉框数据
    getSelections(){
      if(!this.focusQuery || (this.optionsData && this.optionsData.length)) return
      this.remoteSelections(this.selLable || '')
    },
    // 远程搜索
    remoteSelections(query) {
      const defaultProps = this.props || { label: 'label', value: 'value' }
      const rqUrl = this.remoteUrl
      const rqParam = this.paramField || ''
      const rqMethod = this.requestMethod || 'get'
      this.remoteLoading = true
      /* this.optionsData = [
        {value:'1',label:'测试数据1'}
      ]
      this.remoteLoading = false
      return */
      getRemoteData(rqMethod,rqUrl,{[rqParam]:query}).then(res => {
        const dataList = res.data && res.data.map(item => {
          return { value: item[defaultProps.value], label: item[defaultProps.label] }
        })
        this.optionsData = dataList
        this.remoteLoading = false
      }).catch(()=>{
        this.remoteLoading = false
        this.optionsData = []
      })
    },
    handleTabClick(){

    },
    // 查询表格数据
    queryTableData(){
      const params = new FormData()
      params.append('page', this.page)
      params.append('rows', this.pageSize)
      params.append('sort', this.config.sort || '')
      params.append('order', this.config.order || 'desc')
      params.append('paramsRaw',JSON.stringify({nickname:this.queryKeyWord}))
      // params.append('paramsRaw',JSON.stringify({paramKeyword:this.queryKeyWord}))
      getTableData(this.config.interfacePath,params).then(res=>{
        const records = (res.data && res.data.records) || []
        this.loadMore = records.length === this.pageSize
        this.tableData = this.page===1 ? records : this.tableData.concat(records)
      }).catch(() => {
        
      });
    },
    // 加载更多
    handlerLoadMore(){
      this.page += 1
      this.queryTableData()
    },
    // 搜索
    handleSearch(){
      this.page=1
      this.queryTableData()
    },
    // 点击表格行选中
    tableRowHandle(row, column, event) {
      if(this.multiple) return
      this.singleRows=[row]
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedRows.filter(v => v[this.primaryKey] === row[this.primaryKey])
      return filterArr.length > 0 ? 'selected-highlight' : ''
    },
    // 处理选项更新
    handleSelectionChange(rows){
      const cancelArr = this.tableSelectedData.map(data => {
        const index = rows.findIndex(row => row[this.primaryKey]  === data[this.primaryKey] )
        return index === -1 ? data : false
      })

      if (cancelArr && cancelArr.length > 0) {
        cancelArr.forEach(row => {
          const rowIndex = this.tableSelectedData.findIndex(v => v[this.primaryKey]  === row[this.primaryKey] )
          if (rowIndex > -1) {
            this.tableSelectedData.splice(rowIndex, 1)
          }
        })
      }

      this.selectedRows = rows
      rows.forEach(row => {
        const rowIndex = this.tableSelectedData.findIndex(v => v[this.primaryKey] === row[this.primaryKey])
        if (rowIndex === -1) {
          this.tableSelectedData.push(row)
        }
      }) 
    },
    // 移除已选择数据
    handleRemoveSelecte(row){
      const rowIndex = this.tableSelectedData.findIndex(v => v[this.primaryKey] === row[this.primaryKey])
      if (rowIndex > -1) {
        this.tableSelectedData.splice(rowIndex, 1)
      }

      const tmp=this.tableData.filter(v=>v[this.primaryKey]===row[this.primaryKey])
       if (tmp.length > 0) { // 在当前页表格数据中则取消选中
        this.$refs.refTable.toggleRowSelection(tmp[0], false)
      } else { // 未在当前表格数据中，则加入到取消选中的数据集中，并从已选数据表中删除
        const index = this.selectedRows.indexOf(row)
        this.selectedRows.splice(index, 1)
      }
    },
    //清空所有已选择数据
    handleClearAll(){
      this.tableSelectedData = []
      this.selectedRows.map(row=>{
        this.$refs.refTable.toggleRowSelection(row, false)
      })
    },
  }
}
</script>
<style lang='scss' scoped>
@import "../../../theme/qup-theme";
.select-with-search{
  width:100%; 
  position: relative;
  // .input-box{
  //   position: absolute;
  //   left:0;
  //   right: 0;
  //   top: 0;
  //   bottom: 0;
  //   z-index:9
  // }
  /deep/ .el-input__suffix{
    width: 26px;
    height: 26px;
    top: 2px;
    background: #fff;
  }
  /deep/ .el-select{
    width: 100%;
    height: 29px;
    .el-input__suffix{
      right: 30px;
    }
  }
  /deep/ .el-input__inner{
    height: 28px;
    line-height: 28px;
  }
  
  /deep/ .el-input.is-focus .el-input__inner{
    border-color: $qup-color-primary !important;
  }

  /deep/ .el-input__inner:focus{
    border-color: $qup-color-primary !important;
  }
  /deep/ .el-select__tags{
    max-height: 26px !important;
    height: 26px !important;
    overflow: hidden;
    white-space:nowrap;
  }
  .qup-select-input-search{
    position: absolute;
    right: 0;
    top: 0;
    z-index: 9;
    width: 35px;
    height: 28px;
    line-height: 30px;
    color: #c0c4cc;
    text-align: center;
    cursor: default;
  }
}


.search-dlg-head{
  display: flex;
  align-items: center;
  justify-content: space-between;
  /deep/ .el-input.is-active .el-input__inner, 
  /deep/ .el-input__inner:focus{
    border-color:$qup-color-primary !important;
  }
}
.qup-search-dlg{
  /deep/ .el-tabs__active-bar{
    background-color:$qup-color-primary;
  }
  /deep/ .el-tabs__item{
    line-height: 18px;
    height: 24px;
  }
  
  /deep/ .el-tabs__item:hover{
    color:$qup-color-primary;
  } 
  /deep/ .el-tabs__item.is-active{
    color:$qup-color-primary;
    font-weight: bold;
  }
  .btn-load-more{
    margin-top: 10px;
    padding: 0 !important;
    color:$qup-color-primary;
  }
  .btn-submit{
    background-color:$qup-color-primary;
    border-color:$qup-color-primary;
  }
  .btn-clear{
    cursor: pointer;
    color:$qup-color-primary;
  }
  .no-more{
    margin-top: 10px;
    height: 28px;
    line-height: 28px;
    color: #bebebe;
  }
  .btn-remove{
    cursor: pointer;
    font-size: 18px;
    color: #bebebe;
    &:hover{
      color:$qup-color-primary;
    }
  }
}
</style>
